#include <iostream>
#include <cerrno>
#include <cstdio>
#include <cassert>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "command.hpp"

using namespace std;

void writeData()
{
    // 1、打开有名管道(只写)
    int wfd = open(fifo_name.c_str(), O_WRONLY | O_TRUNC);
    if (wfd == -1)
    {
        cerr << "open fail!" << " errno " << errno << ": strerror" << strerror(errno) << endl;
        return;
    }

    cout << "wfd " << wfd << endl;
 
    // 2、进行通信
    cout << "管道文件打开成功，开始通信" << endl;
    char buffer[NUM] = {0}; // 缓冲区

    while (true)
    {
        buffer[0] = 0;
        cout << "Client send# ";
        char* ps = fgets(buffer, sizeof buffer, stdin);
        if(!ps)
        {
            cerr << "fgets fail!" << " errno " << errno << ": strerror" << strerror(errno) << endl;
            return;
        }

        buffer[strlen(buffer) - 1] = '\0';  //需要把 '\n' 移除
        if(strcasecmp(buffer, "quit") == 0)
        {
            //关闭写端
            close(wfd);
            cout << "服务端(client)已关闭！"<< endl;
            break;
        }

        ssize_t n = write(wfd, buffer, strlen(buffer));
        assert(n >= 0);
        (void)n;

        // // 逐字符写入(不依靠回车)
        // system("stty raw");
        // int c = getchar();
        // system("stty -raw");

        // ssize_t n = write(wfd, (char *)&c, sizeof(char));
        // assert(n >= 0);
        // (void)n;
    }

    // 通信结束后，关闭 fd
    close(wfd);
}

int main()
{
    writeData();
    return 0;
}